import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hello_flutter/bloc_demo/weather/theme_bloc/index.dart';
import 'package:hello_flutter/bloc_demo/weather/weather_bloc/index.dart';

import 'city_selection_page.dart';
import 'gradient_container_widget.dart';
import 'last_updated.dart';
import 'location_widget.dart';
import 'settings_page.dart';
import 'weather_temperature_widget.dart';

class WeatherPage extends StatefulWidget {
  State<WeatherPage> createState() => _WeatherPageState();
}

class _WeatherPageState extends State<WeatherPage> {
  Completer<void> _refreshCompleter;

  @override
  void initState() {
    super.initState();
    _refreshCompleter =
        Completer<void>(); // add refresh complete for pull fresh
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Weather'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.settings),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => SettingsPage(),
                ),
              );
            },
          ),
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () async {
              final city = await Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => CitySelection(),
                ),
              );
              if (city != null) {
                BlocProvider.of<WeatherBloc>(context)
                    .add(FetchWeather(city: city));
              }
            },
          )
        ],
      ),
      body: Center(
        // converted our BlocBuilder into a BlocConsumer because we need to handle both rebuilding the UI based on state changes as well as performing side-effects (completing the Completer).
        child: BlocConsumer<WeatherBloc, WeatherState>(
          listener: (context, state) {
            // 监听 状态的变化
            if (state is WeatherLoaded) {
              _refreshCompleter?.complete();
              _refreshCompleter = Completer();
            }
          },
          builder: (context, state) {
            if (state is WeatherEmpty) {
              return Center(child: Text('Please Select a Location'));
            }
            if (state is WeatherLoading) {
              return Center(child: CircularProgressIndicator());
            }
            if (state is WeatherLoaded) {
              final weather = state.weather;
              // use our GradientContainer in our Weather widget to update theme with themsate
              return BlocBuilder<ThemeBloc, ThemeState>(
                  builder: (context, themeState) {
                return GradientContainer(
                    color: themeState.color,
                    //  wrap the ListView in a RefreshIndicator
                    child: RefreshIndicator(
                        onRefresh: () {
                          BlocProvider.of<WeatherBloc>(context).add( RefreshWeather(city: state.weather.location));
                          return _refreshCompleter.future;
                        },
                        child: ListView(
                          children: <Widget>[
                            Padding(
                              padding: EdgeInsets.only(top: 100.0),
                              child: Center(
                                child: Location(location: weather.location),
                              ),
                            ),
                            Center(
                              child: LastUpdated(dateTime: weather.lastUpdated),
                            ),
                            Padding(
                              padding: EdgeInsets.symmetric(vertical: 50.0),
                              child: Center(
                                child: CombinedWeatherTemperature(
                                  weather: weather,
                                ),
                              ),
                            ),
                          ],
                        )));
              });
            }
            if (state is WeatherError) {
              return Text(
                'Something went wrong!',
                style: TextStyle(color: Colors.red),
              );
            }
            return Text(
              'State Error',
              style: TextStyle(color: Colors.red),
            );
          },
        ),
      ),
    );
  }
}
